class Solution {
public:
    int m, n;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    bool vis[101][101] = { 0 };

    bool dfs(int i, int j, vector<string>& board, string word, int pos)
    {
        if (pos == word.size() - 1)
            return true;

        vis[i][j] = true;
        for (int k = 0; k < 4; k++)
        {
            int a = i + dx[k], b = j + dy[k];
            if (a >= 0 && a < m && b >= 0 && b < n && board[a][b] == word[pos + 1] && !vis[a][b])
                if (dfs(a, b, board, word, pos + 1))
                    return true;
        }
        vis[i][j] = false;

        return false;
    }

    bool exist(vector<string>& board, string word) {
        m = board.size(), n = board[0].size();

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == word[0])
                    if (dfs(i, j, board, word, 0))
                        return true;
            }
        }

        return false;
    }
};
